<?php

/**
 *   OPENSHOP 呼叫中心管理程序
 * 
 *   @link        http://baison.com.cn
 *   @copyright   Baison, Inc.
 *   @package     OpenShop
 *   @version     $Id: callcenter.php,v 1.0 2009/07/20 08:36:58 $
 *   @author      Jiajun <jiajun@baison.com.cn>
 */

define('IN_OS', true);
require(dirname(__FILE__) . '/includes/init.php'); 
require_once(SOURCE_PATH . 'languages/' .$_CFG['lang']. '/user.php');

/* 检查权限 */
admin_priv('callcenter');

$phoneNumber = '';

/* act操作项的初始�? */
if (empty($_REQUEST['act']))
{
    $_REQUEST['act'] = 'info';
}
else
{
    $_REQUEST['act'] = trim($_REQUEST['act']);
}

$act = $_REQUEST['act'];
$phoneNumber = $_REQUEST['callerid'];

if($phoneNumber == '' || empty($phoneNumber)){
	sys_msg('没有输入电话号码参数.');
}

$where = ' where office_phone = '.$phoneNumber.' or home_phone = '.$phoneNumber.' or mobile_phone = '.$phoneNumber;
$smarty->assign('phone',     $phoneNumber);	
	
$user_id = get_userid_by_phone($where);

if ($user_id > 0) {
	$r_flag = 1;
}else{
	if ($act != 'add_info'){
		$r_flag = 0;
		$act = 'info';		
	}
}

/*------------------------------------------------------ */
//- 用户信息
/*------------------------------------------------------ */
if ($act == 'info')
{

	$user = ''; 
	if ($user_id > 0) {
    	$smarty->assign('extra_attribute',    build_user_attr_html($user_id));
    	$smarty->assign('profile', get_profile($user_id));
    	$smarty->assign('r_flag',     $r_flag);
	}else{
		// 注册新的用户
		$smarty->assign('r_flag',     $r_flag);
	}

    $ranks = array();
    $ranks = $db->getAll("SELECT * FROM " .$os->table('user_rank').' where special_rank = 1');	
	$smarty->assign('ranks',     $ranks);
    
    
	$page_title = '客服服务管理-呼叫中心';
	$smarty->assign('act',     $act);
	$smarty->assign('phone',     $phoneNumber);
    $smarty->assign('page_title',     $page_title);
	$smarty->display('callcenter.tpl');
	
}

/*------------------------------------------------------ */
//-- 添加新的用户
/*------------------------------------------------------ */
elseif ($act == 'add_info')
{

    $user_rank = isset($_POST['user_rank']) ? trim($_POST['user_rank']) : '';
    $nick_name = isset($_POST['nick_name']) ? trim($_POST['nick_name']) : '';
    $birthday  = isset($_POST['birthday']) ? trim($_POST['birthday']) : '';
    $username  = isset($_POST['user_name']) ? trim($_POST['user_name']) : '';
    $password  = isset($_POST['pwd1']) ? trim($_POST['pwd1']) : '';
    $sex       = isset($_POST['sex']) ? intval(trim($_POST['sex'])) : '';
    $email 	   = isset($_POST['email']) ? trim($_POST['email']) : '';
    $msn 	   = isset($_POST['msn']) ? trim($_POST['msn']) : '';
    $email     = isset($_POST['email']) ? trim($_POST['email']) : '';
    $qq 	   = isset($_POST['qq']) ? trim($_POST['qq']) : '';
    $office_phone = isset($_POST['office_phone']) ? trim($_POST['office_phone']) : '';
    $home_phone    = isset($_POST['home_phone']) ? trim($_POST['home_phone']) : '';
    $mobile_phone = isset($_POST['mobile_phone']) ? trim($_POST['mobile_phone']) : '';
    $discount = isset($_POST['discount']) ? trim($_POST['discount']) : '';
    $user_money    = isset($_POST['user_money']) ? trim($_POST['user_money']) : '';    
    $reg_time =  gmtime(); 

    if (strlen($username) < 3)
    {
        sys_msg($_LANG['passport_js']['username_shorter']);
    }

    if (strlen($password) < 6)
    {
        sys_msg($_LANG['passport_js']['password_shorter']);
    }

    /* �?查注册是否关�? */
    if (!empty($GLOBALS['_CFG']['shop_reg_closed']))
    {
        $GLOBALS['err']->add('该网店暂停注�?');
    }
    /* �?查username */
    if (empty($username))
    {
        $GLOBALS['err']->add($GLOBALS['_LANG']['username_empty']);
    }
    else
    {
        if (preg_match('/\'\/^\\s*$|^c:\\\\con\\\\con$|[%,\\*\\"\\s\\t\\<\\>\\&\'\\\\]/', $username))
        {
            $GLOBALS['err']->add(sprintf($GLOBALS['_LANG']['username_invalid'], htmlspecialchars($username)));
        }
    }

    /* �?查是否和管理员重�? */
    if (admin_registered($username))
    {
        $GLOBALS['err']->add(sprintf($GLOBALS['_LANG']['username_exist'], $username));
        return false;
    }
        
    /* �?查email */
    if (empty($email))
    {
        $GLOBALS['err']->add($GLOBALS['_LANG']['email_empty']);
    }
    else
    {
        if (!is_email($email))
        {
            $GLOBALS['err']->add(sprintf('邮件地址非法�?', htmlspecialchars($email)));
        }
    }
         
	$password = compile_password(array('password'=>$password));
	
	$sql = 'select count(*) from '.$os->table('users').' where user_name = "'.$username.'" or office_phone = '.$phoneNumber.' or home_phone = '.$phoneNumber.' or mobile_phone = '.$phoneNumber;
	$res = $db->getOne($sql);
	
	if($res == 1){
		sys_msg('已经存在一个相同的客户名。');
	}
    
	$sql = "INSERT INTO ".$os->table('users')." (nick_name, email, user_name, password, sex, birthday, user_money, reg_time, user_rank, msn, qq, office_phone, home_phone, mobile_phone) VALUES ('".$nick_name."','".$email."','".$username."','".$password."',".$sex.",'".$birthday."','".$user_money."','".$reg_time."','".$user_rank."','".$msn."','".$qq."','".$office_phone."','".$home_phone."','".$mobile_phone."')";

	$db->query($sql);    
    
    $where = " where user_name = '".$username."'";
    $user_id = get_userid_by_name($where);
    $smarty->assign('extra_attribute',    build_user_attr_html($user_id));
    $smarty->assign('profile', get_profile($user_id));

    $url = '<a target="_blank" href="users.php?act=edit&id='.$user_id.'">编辑客户属性</a>';
    
    $smarty->assign('url',$url);
    
    $smarty->assign('act',     $act);
    $smarty->assign('r_flag',     1);
    $smarty->assign('msg',     '添加新客户成功');

    $smarty->display('callcenter.tpl');	
	
}

/*------------------------------------------------------ */
//-- 交易记录
/*------------------------------------------------------ */
elseif ($act == 'traderecord')
{

    $page = isset($_REQUEST['page']) ? intval($_REQUEST['page']) : 1;

    $record_count = $db->getOne("SELECT COUNT(*) FROM " .$os->table('order_info'). " WHERE user_id = '$user_id'");

    //$pager  = get_pager('user.php', array('act' => $action), $record_count, $page);
	
    $orders = get_user_orders($user_id, $pager['size'], $pager['start']);
	
    $merge  = get_user_merge($user_id);

    $smarty->assign('merge',  $merge);
    //$smarty->assign('pager',  $pager);
    $smarty->assign('orders', $orders);	
	
    $smarty->assign('act',     $act);
    $smarty->assign('orders', $orders);

    $smarty->display('callcenter.tpl');	
	
}

/*------------------------------------------------------ */
//-- 交易详细
/*------------------------------------------------------ */
elseif ($act == 'trade_detail')
{

    $order_id = isset($_GET['order_id']) ? intval($_GET['order_id']) : 0;

    /* 订单详情 */
    $order = get_order_detail($order_id, $user_id);

    if ($order === false)
    {
        $err->show($_LANG['back_home_lnk'], './');

        exit;
    }

    /* 是否显示添加到购物车 */
    if ($order['extension_code'] != 'group_buy' && $order['extension_code'] != 'exchange_goods')
    {
        $smarty->assign('allow_to_cart', 1);
    }

    /* 订单商品 */
    $goods_list = order_goods($order_id);

    foreach ($goods_list AS $key => $value)
    {
        $goods_list[$key]['market_price'] = price_format($value['market_price'], false);
        $goods_list[$key]['goods_price']  = price_format($value['goods_price'], false);
        $goods_list[$key]['subtotal']     = price_format($value['subtotal'], false);
    }

     /* 设置能否修改使用余额�? */
    if ($order['order_amount'] > 0)
    {
        if ($order['order_status'] == OS_UNCONFIRMED || $order['order_status'] == OS_CONFIRMED)
        {
            $user = user_info($order['user_id']);
            if ($user['user_money'] + $user['credit_line'] > 0)
            {
                $smarty->assign('allow_edit_surplus', 1);
                $smarty->assign('max_surplus', sprintf($_LANG['max_surplus'], $user['user_money']));
            }
        }
    }

    /* 未发货，未付款时允许更换支付方式 */
    if ($order['order_amount'] > 0 && $order['pay_status'] == PS_UNPAYED && $order['shipping_status'] == SS_UNSHIPPED)
    {
        $payment_list = available_payment_list(false, 0, true);

        /* 过滤掉当前支付方式和余额支付方式 */
        foreach ($payment_list as $key => $payment)
        {
            if ($payment['pay_id'] == $order['pay_id'] || $payment['pay_code'] == 'balance')
            {
                unset($payment_list[$key]);
            }
        }
        $smarty->assign('payment_list', $payment_list);
    }

    /* 订单 支付 配�?? 状�?�语�?�? */
    $order['order_status'] = $_LANG['os'][$order['order_status']];
    $order['pay_status'] = $_LANG['ps'][$order['pay_status']];
    $order['shipping_status'] = $_LANG['ss'][$order['shipping_status']];

    $smarty->assign('act',     $act);
    $smarty->assign('order',      $order);
    $smarty->assign('goods_list', $goods_list);

    $smarty->display('callcenter.tpl');	
	
}


/*------------------------------------------------------ */
//-- 来电记录
/*------------------------------------------------------ */
elseif ($act == 'callrecord')
{
	$seat_number = $_REQUEST['CallRecordId'];
	
	$call_record = get_call_record($user_id);
	$user_name = get_username_by_id($user_id);
	$act_staff = $_SESSION['admin_name'];
	
	$smarty->assign('act',     $act);
	$smarty->assign('act_staff',     $act_staff);
	$smarty->assign('user_name',     $user_name);
	$smarty->assign('call_record',     $call_record);
	$smarty->assign('seat_number',     $seat_number);
	$smarty->display('callcenter.tpl');
}

/*------------------------------------------------------ */
//-- 添加新的电话记录
/*------------------------------------------------------ */
elseif ($act == 'add_callrecord')
{
    $call_number = isset($_POST['call_number']) ? trim($_POST['call_number']) : '';
    $record_type = isset($_POST['record_type']) ? trim($_POST['record_type']) : '';	
    $email  = isset($_POST['email']) ? trim($_POST['email']) : '';
    $phone_number       = isset($_POST['phone_number']) ? intval(trim($_POST['phone_number'])) : '';
    $cell_number 	   = isset($_POST['cell_number']) ? trim($_POST['cell_number']) : '';
    $address 	   = isset($_POST['address']) ? trim($_POST['address']) : '';
    $act_staff     = isset($_POST['act_staff']) ? trim($_POST['act_staff']) : '';
    $qq 	   = isset($_POST['qq']) ? trim($_POST['qq']) : '';
    $seat_number = isset($_POST['seat_number']) ? trim($_POST['seat_number']) : '';
    $record_time =  gmtime(); 
    
    $phoneNumber = $call_number;
	$where = ' where office_phone = '.$phoneNumber.' or home_phone = '.$phoneNumber.' or mobile_phone = '.$phoneNumber;
    $user_id = get_userid_by_phone($where);
    $user_name = get_username_by_id($user_id);
    
	$sql = "INSERT INTO ".$os->table('call_record')." (user_id, nick_name, user_name, email, record_time, record_type, call_number, seat_number, phone_number, cell_number, act_staff, address) VALUES ('".$user_id."','".$user_name."','".$user_name."','".$email."',".$record_time.",'".$record_type."','".$call_number."','".$seat_number."','".$phone_number."','".$cell_number."','".$act_staff."','".$address."')";

    $db->query($sql);    
    
	$call_record = get_call_record($user_id);
	
	$act_staff = $_SESSION['admin_name'];
	
	$smarty->assign('act',     $act);
	$smarty->assign('act_staff',     $act_staff);   
	$smarty->assign('user_name',     $user_name);
	$smarty->assign('seat_number',     $seat_number);
	$smarty->assign('call_record',     $call_record);
	
    $smarty->assign('r_flag',     1);
    $smarty->assign('msg',     '添加来电记录成功');

    $smarty->display('callcenter.tpl');	
	
}  

/*------------------------------------------------------ */
//-- 客户问答
/*------------------------------------------------------ */
elseif ($act == 'interact')
{
	$call_record_id = trim($_REQUEST['call_record_id']);
	
	$interact_list = get_interact_list($phoneNumber);
		
	$act_staff = $_SESSION['admin_name'];
	
	$smarty->assign('act',     $act);
	$smarty->assign('act_staff',     $act_staff);  
	$smarty->assign('interact_list',     $interact_list);
	$smarty->assign('call_record_id',     $call_record_id);
	$smarty->display('callcenter.tpl');
}

/*------------------------------------------------------ */
//-- 客户问答添加
/*------------------------------------------------------ */
elseif ($act == 'add_interact')
{
	$in_use = intval(trim($_REQUEST['in_use']));	
	$txtAnswer = trim($_REQUEST['txtAnswer']);	
	$txtQuestion = trim($_REQUEST['txtQuestion']);
	$call_record_id = trim($_REQUEST['call_record_id']);	
	$add_time = gmtime();
	
	$act_staff = trim($_POST['act_staff']);
	
	$sql = "INSERT INTO ".$os->table('call_interact')." (call_record_id, question, answer, in_use, add_time,act_staff) ".
           "VALUES ('".$phoneNumber."', '".$txtQuestion."', '$txtAnswer', '$in_use', '$add_time', '$act_staff')";

    $db->query($sql);

    $interact_list = get_interact_list($phoneNumber);
 
    $smarty->assign('msg',     '添加客户问答记录成功');
	$act_staff = $_SESSION['admin_name'];
	
	$smarty->assign('act',     $act);
	$smarty->assign('act_staff',     $act_staff);    
	$smarty->assign('interact_list',     $interact_list);    
    $smarty->assign('call_record_id',     $call_record_id);
	$smarty->display('callcenter.tpl');
}

function get_userid_by_name($where){
	$sql = 'select user_id from '.$GLOBALS['os']->table('users').$where;
	$user_id = $GLOBALS['db']->getOne($sql);
	return $user_id;
}

function get_userid_by_phone($where){
	$sql = 'select user_id from '.$GLOBALS['os']->table('users').$where;
	$user_id = $GLOBALS['db']->getOne($sql);
	return $user_id;
}

function get_username_by_id($user_id){
	$sql = 'select user_name from '.$GLOBALS['os']->table('users').' where user_id = '.$user_id;
	$user_name = $GLOBALS['db']->getOne($sql);
	return $user_name;
}

function get_interact_list($phoneNumber){
	
	$sql = 'select i.* from '.$GLOBALS['os']->table('call_interact').' as i where i.call_record_id = '.$phoneNumber.' order by i.add_time asc';
	
    $res = $GLOBALS['db']->query($sql);
    
    $arr = array();
    
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
      $row['add_time'] = local_date($GLOBALS['_CFG']['time_format'], $row['add_time']);
      $arr[] = $row;
    }

	return $arr;
}

/**
 * 获取用户帐号信息
 *
 * @access  public
 * @param   int       $user_id        用户user_id
 *
 * @return void
 */
function get_profile($user_id)
{
    global $user;

    /* 会员帐号信息 */
    $info  = array();
    $infos = array();
    $sql  = "SELECT user_name, nick_name,email,birthday, sex, question, answer, rank_points, pay_points,user_money, user_rank,  ".
             " msn, qq, office_phone, home_phone, mobile_phone ".
           "FROM " .$GLOBALS['os']->table('users') . " WHERE user_id = '$user_id'";
    $infos = $GLOBALS['db']->getRow($sql);
    $infos['user_name'] = addslashes($infos['user_name']);

    /* 会员等级 */
    if ($infos['user_rank'] > 0)
    {
        $sql = "SELECT rank_id, rank_name, discount FROM ".$GLOBALS['os']->table('user_rank') .
               " WHERE rank_id = '$infos[user_rank]'";
    }
    else
    {
        $sql = "SELECT rank_id, rank_name, discount, min_points".
               " FROM ".$GLOBALS['os']->table('user_rank') .
               " WHERE min_points<= " . intval($infos['rank_points']) . " ORDER BY min_points DESC";
    }

    if ($row = $GLOBALS['db']->getRow($sql))
    {
        $info['rank_name']     = $row['rank_name'];
    }
    else
    {
        $info['rank_name'] = '没有定义用户等级';
    }

    $cur_date = date('Y-m-d H:i:s');

    /* 会员红包 */
    $bonus = array();
    $sql = "SELECT type_name, type_money ".
           "FROM " .$GLOBALS['os']->table('bonus_type') . " AS t1, " .$GLOBALS['os']->table('user_bonus') . " AS t2 ".
           "WHERE t1.type_id = t2.bonus_type_id AND t2.user_id = '$user_id' AND t1.use_start_date <= '$cur_date' ".
           "AND t1.use_end_date > '$cur_date' AND t2.order_id = 0";
    $bonus = $GLOBALS['db']->getAll($sql);
    if ($bonus)
    {
        for ($i = 0, $count = count($bonus); $i < $count; $i++)
        {
            $bonus[$i]['type_money'] = price_format($bonus[$i]['type_money'], false);
        }
    }

    $info['discount']    = $infos['discount'] * 100 . "%"; 
    $info['email']       = $infos['email'];
    $info['user_name']   = $infos['user_name'];
    $info['nick_name']   = $infos['nick_name'];
    $info['rank_points'] = isset($infos['rank_points']) ? $infos['rank_points'] : '';
    $info['pay_points']  = isset($infos['pay_points'])  ? $infos['pay_points']  : 0;
    $info['user_money']  = isset($infos['user_money'])  ? $infos['user_money']  : 0;
    $info['sex']         = isset($infos['sex'])      ? $infos['sex']      : 0;
    $info['birthday']    = isset($infos['birthday']) ? $infos['birthday'] : '';
    $info['question']    = isset($infos['question']) ? htmlspecialchars($infos['question']) : '';

    $info['user_money']  = price_format($info['user_money'], false);
    $info['pay_points']  = $info['pay_points'] . $GLOBALS['_CFG']['integral_name'];
    $info['bonus']       = $bonus;
    $info['qq']          = $infos['qq'];
    $info['msn']          = $infos['msn'];
    $info['office_phone']= $infos['office_phone'];
    $info['home_phone']   = $infos['home_phone'];
    $info['mobile_phone'] = $infos['mobile_phone'];

    return $info;
}

function build_user_attr_html($user_id)
{
    $sql = " select u_attr.attr_id, attr_name, attr_input_type,attr_type,attr_values,sort_order,attr_value".
		  " from ". $GLOBALS['os']->table('user_attribute'). "as u_attr" .
		  " left join ".$GLOBALS['os']->table('user_attribute_value')." as u_value ".
		  " on u_value.attr_id = u_attr.attr_id and u_value.user_id =".$user_id." order by attr_type asc";
    $attr = $GLOBALS['db']->GetAll($sql);
    
    $html = '<table width="100%" id="attrTable">';
    $spec = 0;

    foreach ($attr AS $key => $val)
    {
        $html .= "<tr><td class='label'>";

		$html .= "$val[attr_name]</td><td>";
        if ($val['attr_input_type'] == 0)
        {
            $html .= '<input name="'.$val['attr_id'].'" type="text" value="' .htmlspecialchars($val['attr_value']). '" size="40" /> ';
        }
        elseif ($val['attr_input_type'] == 2)
        {
            $html .= '<textarea name="'.$val['attr_id'].'" rows="3" cols="40">' .htmlspecialchars($val['attr_value']). '</textarea>';
        }
        elseif ($val['attr_type'] == 2 & $val['attr_input_type'] == 1){
        	$attr_values = explode("\n", $val['attr_values']);
        	$attr_value  = explode(" ", $val['attr_value']);
        	foreach ($attr_values AS $opt)
            {
            	$opt   = trim(htmlspecialchars($opt));
            	$is_checked = in_array($opt,$attr_value)?'checked':'';
                $html .= "<input type='checkbox' name='".$val['attr_id']."[]' value='".$opt."'".$is_checked." >&nbsp;&nbsp;".$opt."&nbsp;&nbsp;";	
            }
        }else{
            $html .= '<select name="'.$val['attr_id'].'">';
            $html .= '<option value="">' .$GLOBALS['_LANG']['select_please']. '</option>';

            $attr_values = explode("\n", $val['attr_values']);

            foreach ($attr_values AS $opt)
            {
                $opt    = trim(htmlspecialchars($opt));

                $html   .= ($val['attr_value'] != $opt) ?
                    '<option value="' . $opt . '">' . $opt . '</option>' :
                    '<option value="' . $opt . '" selected="selected">' . $opt . '</option>';
            }
            $html .= '</select> ';
        }

        $html .= '</td></tr>';
    }

    $html .= '</table>';

    return $html;
}

function get_user_orders($user_id, $num = 10, $start = 0)
{
    /* 取得订单列表 */
    $arr    = array();

    $sql = "SELECT order_id, order_sn, order_status, extension_code,shipping_status, pay_status, add_time, " .
           "(goods_amount + shipping_fee + insure_fee + pay_fee + pack_fee + card_fee + tax - discount) AS total_fee ".
           " FROM " .$GLOBALS['os']->table('order_info') .
           " WHERE user_id = '$user_id' ORDER BY add_time DESC";

    $res = $GLOBALS['db']->query($sql);

    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        if ($row['order_status'] == OS_UNCONFIRMED)
        {
            $row['handler'] = "<a href=\"user.php?act=cancel_order&order_id=" .$row['order_id']. "\" onclick=\"if (!confirm('".$GLOBALS['_LANG']['confirm_cancel']."')) return false;\">".$GLOBALS['_LANG']['cancel']."</a>";
        }
        else if ($row['order_status'] == OS_CONFIRMED)
        {
        	if ($row['pay_status'] == PS_UNPAYED)
        	{
        		@$row['handler'] = "<a href=\"user.php?act=order_detail&order_id=" .$row['order_id']. '">' .$GLOBALS['_LANG']['pay_money']. '</a>';
        	}
        	else
        	{
        		@$row['handler'] = "<a href=\"user.php?act=order_detail&order_id=" .$row['order_id']. '">' .$GLOBALS['_LANG']['view_order']. '</a>';
        	}
        }
        else
        {
            $row['handler'] = '<span style="color:red">'.$GLOBALS['_LANG']['os'][$row['order_status']] .'</span>';
        }
        $row['order_status'] = $GLOBALS['_LANG']['os'][$row['order_status']] . ',' . $GLOBALS['_LANG']['ps'][$row['pay_status']] . ',' . $GLOBALS['_LANG']['ss'][$row['shipping_status']];

        $arr[] = array('order_id'       => $row['order_id'],
                       'order_sn'       => $row['order_sn'],
                       'order_time'     => local_date($GLOBALS['_CFG']['time_format'], $row['add_time']),
                       'order_status'   => $row['order_status'],
                       'total_fee'      => price_format($row['total_fee'], false),
                       'extension_code' => $row['extension_code'],
                       'handler'        => $row['handler']);
    }

    return $arr;
}

function get_user_merge($user_id)
{
    include_once(ROOT_PATH . 'includes/lib_order.php');
    $sql  = "SELECT order_sn FROM ".$GLOBALS['os']->table('order_info') .
            " WHERE user_id  = '$user_id' " . order_query_sql('unprocessed') .
                "AND extension_code = '' ".
            " ORDER BY add_time DESC";
    $list = $GLOBALS['db']->GetCol($sql);

    $merge = array();
    foreach ($list as $val)
    {
        $merge[$val] = $val;
    }

    return $merge;
}

function get_call_record($user_id)
{
    $sql  = "SELECT r.* FROM ".$GLOBALS['os']->table('call_record') .
            " as r WHERE r.user_id  = ".$user_id." ORDER BY record_time DESC";
    $list = $GLOBALS['db']->getAll($sql);

	foreach ($list AS $key => $value)
	{
		$list[$key]['record_time'] = local_date($GLOBALS['_CFG']['time_format'], $value['record_time']);
	}
     
    return $list;
}

function get_order_detail($order_id, $user_id = 0)
{
    include_once(ROOT_PATH . 'includes/lib_order.php');

    $order_id = intval($order_id);
    if ($order_id <= 0)
    {
        $GLOBALS['err']->add($GLOBALS['_LANG']['invalid_order_id']);

        return false;
    }
    $order = order_info($order_id);

    //�?查订单是否属于该用户
    if ($user_id > 0 && $user_id != $order['user_id'])
    {
        $GLOBALS['err']->add($GLOBALS['_LANG']['no_priv']);

        return false;
    }

    /* 对发货号处理 */
    if (!empty($order['invoice_no']))
    {
         $shipping_code = $GLOBALS['db']->GetOne("SELECT shipping_code FROM ".$GLOBALS['os']->table('shipping') ." WHERE shipping_id = '$order[shipping_id]'");
         $plugin = ROOT_PATH.'includes/modules/shipping/'. $shipping_code. '.php';
         if (file_exists($plugin))
        {
              include_once($plugin);
              $shipping = new $shipping_code;
              $order['invoice_no'] = $shipping->query($order['invoice_no']);
        }
    }

    /* 只有未确认才允许用户修改订单地址 */
    if ($order['order_status'] == OS_UNCONFIRMED)
    {
        $order['allow_update_address'] = 1; //允许修改收货地址
    }
    else
    {
        $order['allow_update_address'] = 0;
    }

    /* 获取订单中实体商品数�? */
    $order['exist_real_goods'] = exist_real_goods($order_id);

    /* 如果是未付款状�?�，生成支付按钮 */
    if ($order['pay_status'] == PS_UNPAYED &&
        ($order['order_status'] == OS_UNCONFIRMED ||
        $order['order_status'] == OS_CONFIRMED))
    {
        /*
         * 在线支付按钮
         */
        //支付方式信息
        $payment_info = array();
        $payment_info = payment_info($order['pay_id']);

        //无效支付方式
        if ($payment_info === false)
        {
            $order['pay_online'] = '';
        }
        else
        {
            //取得支付信息，生成支付代�?
            $payment = unserialize_config($payment_info['pay_config']);

            //获取�?要支付的log_id
            $order['log_id']    = get_paylog_id($order['order_id'], $pay_type = PAY_ORDER);
            $order['user_name'] = $_SESSION['user_name'];
            $order['pay_desc']  = $payment_info['pay_desc'];

            /* 调用相应的支付方式文�? */
            include_once(ROOT_PATH . 'includes/modules/payment/' . $payment_info['pay_code'] . '.php');

            /* 取得在线支付方式的支付按�? */
            $pay_obj    = new $payment_info['pay_code'];
            $order['pay_online'] = $pay_obj->get_code($order, $payment);
        }
    }
    else
    {
        $order['pay_online'] = '';
    }

    /* 无配送时的处�? */
    $order['shipping_id'] == -1 and $order['shipping_name'] = $GLOBALS['_LANG']['shipping_not_need'];

    /* 其他信息初始�? */
    $order['how_oos_name']     = $order['how_oos'];
    $order['how_surplus_name'] = $order['how_surplus'];

    /* 虚拟商品付款后处�? */
    if ($order['pay_status'] != PS_UNPAYED)
    {
        /* 取得已发货的虚拟商品信息 */
        $virtual_goods = get_virtual_goods($order_id, true);
        $virtual_card = array();
        foreach ($virtual_goods AS $code => $goods_list)
        {
            /* 只处理虚拟卡 */
            if ($code == 'virtual_card')
            {
                foreach ($goods_list as $goods)
                {
                    if ($info = virtual_card_result($order['order_sn'], $goods))
                    {
                        $virtual_card[] = array('goods_id'=>$goods['goods_id'], 'goods_name'=>$goods['goods_name'], 'info'=>$info);
                    }
                }

                $GLOBALS['smarty']->assign('virtual_card',      $virtual_card);
            }
        }
    }

    /* 确认时间 支付时间 发货时间 */
    if ($order['confirm_time'] > 0 && $order['order_status'] == OS_CONFIRMED)
    {
        $order['confirm_time'] = sprintf($GLOBALS['_LANG']['confirm_time'], local_date($GLOBALS['_CFG']['time_format'], $order['confirm_time']));
    }
    else
    {
        $order['confirm_time'] = '';
    }
    if ($order['pay_time'] > 0 && $order['pay_status'] != PS_UNPAYED)
    {
        $order['pay_time'] = sprintf($GLOBALS['_LANG']['pay_time'], local_date($GLOBALS['_CFG']['time_format'], $order['pay_time']));
    }
    else
    {
        $order['pay_time'] = '';
    }
    if ($order['shipping_time'] > 0 && in_array($order['shipping_status'], array(SS_SHIPPED, SS_RECEIVED)))
    {
        $order['shipping_time'] = sprintf($GLOBALS['_LANG']['shipping_time'], local_date($GLOBALS['_CFG']['time_format'], $order['shipping_time']));
    }
    else
    {
        $order['shipping_time'] = '';
    }

    return $order;

}

function get_paylog_id($surplus_id, $pay_type = PAY_SURPLUS)
{
    $sql = 'SELECT log_id FROM' .$GLOBALS['os']->table('pay_log').
           " WHERE order_id = '$surplus_id' AND order_type = '$pay_type' AND is_paid = 0";

    return $GLOBALS['db']->getOne($sql);
}

function compile_password ($cfg)
{
   if (isset($cfg['password']))
   {
       $cfg['md5password'] = md5($cfg['password']);
   }
   if (empty($cfg['type']))
   {
       $cfg['type'] = PWD_MD5;
   }

   switch ($cfg['type'])
   {
       case PWD_MD5 :
           return $cfg['md5password'];

        case PWD_PRE_SALT :
           if (empty($cfg['salt']))
           {
              $cfg['salt'] = '';
           }

           return md5($cfg['salt'] . $cfg['md5password']);

        case PWD_SUF_SALT :
           if (empty($cfg['salt']))
           {
               $cfg['salt'] = '';
           }

           return md5($cfg['md5password'] . $cfg['salt']);

        default:
           return '';
   }
}

function admin_registered( $adminname )
{
    $res = $GLOBALS['db']->getOne("SELECT COUNT(*) FROM " . $GLOBALS['os']->table('admin_user') .
                                  " WHERE user_name = '$adminname'");
    return $res;
}
?>